<?php
/**
 * Created by PhpStorm.
 * User: bevan
 * Date: 2018/2/9
 * Time: 下午2:41
 */

namespace app\admin\service;

use app\common\model\OptionsModel;
use think\Db;
use think\Exception;

class OptionsService
{
    public function index()
    {
        return OptionsModel::all();
    }

    public function update($type, $data)
    {
        Db::startTrans();
        try {
            foreach ($data as $key => $val) {
                $value = [];
                $map['option_name'] = $key;
                $map['type'] = $type;
                $value['option_value'] = $val;
                $value['update_time'] = time();
                $res = OptionsModel::where($map)->find();
                if ($res) {
                    OptionsModel::where($map)->update($value);
                } else {
                    $value = array_merge($map, $value);
                    OptionsModel::create($value);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 4001, 'msg' => '更新失败,' . $e->getMessage(), 'data' => []];
        }
        cmf_clear_cache();
        return ['code' => 1001, 'msg' => '更新成功', 'data' => []];

    }

    public function set($type, $key, $val = '')
    {
        $type = strtolower($type);
        $key = strtolower($key);
        $option = OptionsModel::where('type', strtolower($type))
            ->where('option_name', $key)->setField('option_value',$val);
        if ($option) {
            return ['code' => 1001, 'msg' => '设置成功', 'data' => $data];
        } else {
            return ['code' => 4001, 'msg' => '设置失败', 'data' => []];
        }
    }

    public function read($type = '', $key = '')
    {
        $option = OptionsModel::where('type', strtolower($type));
        $option = $key ? $option->where('option_name', $key) : $option;
        $options = $option
            ->field('option_name,option_value,type')
            ->select();
        if (count($options)) {
            foreach ($options as $option) {
                $data[$option['option_name']] = $option['option_value'];
            }
            return ['code' => 1001, 'msg' => '获取成功', 'data' => $data];
        } else {
            return ['code' => 4001, 'msg' => '获取失败', 'data' => []];
        }

    }

    public function auto()
    {
        $options = OptionsModel::where('autoload', 1)->select();
        if (count($options)) {
            return ['code' => 1001, 'msg' => '获取成功', 'data' => $options];
        } else {
            return ['code' => 4001, 'msg' => '获取失败', 'data' => []];
        }
    }
}
